package scatter.common.rest.service;

import scatter.common.pojo.po.BasePo;
import scatter.common.pojo.po.BaseTreePo;
import scatter.common.rest.mapstruct.IBaseAddFormMapStruct;

import java.util.List;

/**
 * 添加基础父接口
 * Created by yangwei
 * Created at 2021/1/5 9:47
 */
public interface IBaseAddFormService<Po extends BasePo,AddForm> extends IBaseService<Po> {

    IBaseAddFormMapStruct<Po,AddForm> getAddFormMapStruct();

    List<IAddServiceListener<Po,AddForm>> getAddServiceListeners();
    /**
     * 添加前
     * @param addForm
     */
    default void preAdd(AddForm addForm,Po po){}

    /**
     * 添加前
     * @param addForm
     * @param options 预留字段
     */
    default void preAdd(AddForm addForm,Po po,Object options){
        // 树相关
        if (po instanceof BaseTreePo) {
            initParentIdXByParent(po, ((BaseTreePo) po).getParentId());
        }
        preAdd(addForm,po);
        if (!isEmpty(getAddServiceListeners())) {
            getAddServiceListeners().parallelStream().forEach(listener->listener.preAdd(addForm,po));
        }
    }

    /**
     * 添加后
     * @param addForm
     * @param po
     */
    default void postAdd(AddForm addForm,Po po){}

    /**
     * 添加后
     * @param addForm
     * @param po
     * @param options
     */
    default void postAdd(AddForm addForm,Po po,Object options){
        postAdd(addForm,po);
        if (!isEmpty(getAddServiceListeners())) {
            getAddServiceListeners().parallelStream().forEach(listener->listener.postAdd(addForm,po));
        }
    }
    default Po add(AddForm addForm) {
        Po po = getAddFormMapStruct().addFormToPo(addForm);
        preAdd(addForm,po,null);
        boolean r =  save(po);
        if(r){
            postAdd(addForm,po,null);
            return po;
        }else {
            return null;
        }
    }
}
